﻿using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Common
{
    public class FileHelper
    {

    }


    public static class FileHelperExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="stream">文件流</param>
        /// <param name="extension">文件后缀</param>
        /// <param name="userId">上传文件人的id</param>
        /// <param name="fileId">文件的id，要返回去给上一层记录数据库和返回前端</param>
        /// <param name="msg">消息</param>
        /// <returns></returns>
        public static bool UpLoad(this IHelper helper, Stream stream, string extension, string userId, out string fileId, out string msg)
        {
            try
            {
                var _env = helper.GetService<IHostingEnvironment>();

                string path = Path.Combine(_env.WebRootPath, "UpFile", userId);//拼接文件夹

                fileId = Guid.NewGuid().ToString();

                var fileName = fileId + extension;//文件名带后缀

                var filePath = Path.Combine(path, fileName);//完整路径
                //判断是否有文件夹没有就创建
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                //文件写入
                using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    stream.CopyTo(fs);
                }
                msg = "上传文件成功！";
                return true;
            }
            catch (Exception ex)
            {
                
                fileId = "";
                msg = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 下载文件的方法
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="fileName">文件名=文件id+后缀</param>
        /// <param name="creatorId">上传这个文件的人的id</param>
        /// <returns></returns>
        public static Stream DownloadFile(this IHelper helper, string fileName, string creatorId)
        {
            try
            {
                //获取当前项目运行的目录
                var _environment = helper.GetService<IHostingEnvironment>();
                string path = Path.Combine(_environment.WebRootPath, "UpFile", creatorId);//方法更常见，因为它可以方便地获取Web应用程序的根目录

                //拼接路径与文件名
                string filePath = Path.Combine(path, fileName);

                //重新打开文件流去读取要下载的excel文件
                FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                //返回文件流
                return fileStream;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
